const fs = require('fs');
const path = require('path');
const { promisify } = require('util');
const readFile = promisify(fs.readFile);
const writeFile = promisify(fs.writeFile);

// 递归创建目录（如果不存在）
function ensureDirectoryExists(dirPath) {
    if (!fs.existsSync(dirPath)) {
        fs.mkdirSync(dirPath, { recursive: true });
    }
}

// 递归复制目录
function copyRecursiveSync(src, dest) {
    const stats = fs.statSync(src);
    if (stats.isDirectory()) {
        ensureDirectoryExists(dest);
        fs.readdirSync(src).forEach(item => {
            copyRecursiveSync(
                path.join(src, item),
                path.join(dest, item)
            );
        });
    } else {
        fs.copyFileSync(src, dest);
    }
}

// 从HTML内容中提取script和link标签
function extractTags(htmlContent) {
    const scriptRegex = /<script\b[^>]*>([\s\S]*?)<\/script>/gi;
    const linkRegex = /<link\b[^>]*>/gi;

    const scripts = [];
    const links = [];

    let match;
    while ((match = scriptRegex.exec(htmlContent)) !== null) {
        scripts.push(match[0]);
    }
    while ((match = linkRegex.exec(htmlContent)) !== null) {
        links.push(match[0]);
    }

    return { scripts, links };
}

// 将标签注入到目标HTML中
function injectTags(targetHtml, tags) {
    const headEnd = '</head>';
    const bodyEnd = '</body>';

    // 注入link标签到head结束前
    if (tags.links.length > 0) {
        const linksHtml = tags.links.join('\n    ');
        targetHtml = targetHtml.replace(headEnd, `    ${linksHtml}\n${headEnd}`);
    }

    // 注入script标签到body结束前
    if (tags.scripts.length > 0) {
        const scriptsHtml = tags.scripts.join('\n    ');

        // 确保body结束标签存在
        if (targetHtml.includes(bodyEnd)) {
            targetHtml = targetHtml.replace(bodyEnd, `    ${scriptsHtml}\n${bodyEnd}`);
        } else {
            // 如果不存在body结束标签，直接追加到文件末尾
            targetHtml += `\n${scriptsHtml}\n`;
        }
    }

    return targetHtml;
}

// 删除特定的script标签
function removeSpecificScriptTag(htmlContent) {
    // 要删除的script标签
    const targetScript = '<script type="module" src="/matechat/src/main.ts"></script>';

    // 尝试直接匹配
    if (htmlContent.includes(targetScript)) {
        return htmlContent.replace(targetScript, '');
    }

    // 如果直接匹配失败，尝试使用更灵活的正则表达式
    const regex = /<script\s+type="module"\s+src="\/matechat\/src\/main\.ts"\s*>\s*<\/script>/i;
    return htmlContent.replace(regex, '');
}

async function main() {
    try {
        const baseDir = process.cwd();
        console.log('开始文件复制操作...');

        // 1. 复制Angular文件
        const angularSrc = path.join(baseDir, '../Angular/dist/angular/browser');
        const angularDest = path.join(baseDir, '../Node/dist');
        console.log(`复制Angular文件: ${angularSrc} -> ${angularDest}`);
        copyRecursiveSync(angularSrc, angularDest);

        // 2. 复制Vue文件
        const vueSrc = path.join(baseDir, '../Vue/dist');
        const vueDest = path.join(baseDir, '../Node/dist/matechat');
        console.log(`复制Vue文件: ${vueSrc} -> ${vueDest}`);
        copyRecursiveSync(vueSrc, vueDest);

        // 3. 处理HTML文件
        const vueHtmlPath = path.join(vueDest, 'index.html');
        const targetHtmlPath = path.join(angularDest, 'index.html');

        console.log(`读取Vue HTML文件: ${vueHtmlPath}`);
        const vueHtml = await readFile(vueHtmlPath, 'utf8');

        console.log('提取script和link标签');
        const tags = extractTags(vueHtml);
        console.log(`找到 ${tags.scripts.length} 个script标签, ${tags.links.length} 个link标签`);

        console.log(`读取目标HTML文件: ${targetHtmlPath}`);
        let targetHtml = await readFile(targetHtmlPath, 'utf8');

        console.log('注入标签到目标HTML');
        targetHtml = injectTags(targetHtml, tags);

        // 4. 删除特定的script标签
        console.log('删除特定的script标签');
        targetHtml = removeSpecificScriptTag(targetHtml);

        console.log(`写入更新后的HTML文件: ${targetHtmlPath}`);
        await writeFile(targetHtmlPath, targetHtml);

        console.log('所有操作已完成！');
    } catch (error) {
        console.error('操作失败:', error);
        process.exit(1);
    }
}

main();